package org.xukai.remoting.netty.runtime;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.ReferenceCountUtil;
import org.xukai.remoting.netty.serial.Resp;
import org.xukai.remoting.utils.GzipUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class ClientHandler extends ChannelHandlerAdapter{
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) {
		String readPath = System.getProperty("user.dir") + File.separatorChar + "basic-remoting" + File.separatorChar
				+ "sources" +  File.separatorChar +	"006.jpg";
		File file = new File(readPath);
		FileInputStream in = null;
		try {
			in = new FileInputStream(file);
			byte[] data = new byte[in.available()];
			in.read(data);
			in.close();
			byte[] bytes = GzipUtils.gzip(data);
			Request request = new Request();
			request.setName("测试发送大文件");
			request.setAttachment(bytes);
			ctx.channel().writeAndFlush(request);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

//		for(int i = 1; i <= 3; i++ ){
//			Request request = new Request();
//			request.setId("" + i);
//			request.setName("pro" + i);
//			request.setRequestMessage("数据信息" + i);
//			ctx.channel().writeAndFlush(request);
//			TimeUnit.SECONDS.sleep(4);
//		}
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		try {
			Response resp = (Response)msg;
			System.out.println("Client : " + resp.getId() + ", " + resp.getName() + ", " + resp.getResponseMessage());			
		} finally {
			ReferenceCountUtil.release(msg);
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
	
}
